﻿using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface.IManagement;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentAgriculture.Domain.Impl.Managements
{
    public class ManageRepository : IManageRepository
    {
        public readonly AgricultureDbContext _context;
        public ManageRepository(AgricultureDbContext context)
        {
            _context = context;
        }

        public IQueryable<Management> GetShow()
        {
            return _context.Managements.AsQueryable().AsNoTracking();
        }

        /// <summary>
        /// 添加功能
        /// </summary>
        /// <param name="entity">添加实体</param>
        /// <returns></returns>
        public Task<int> Add(Management entity)
        {
            try
            {
                entity.CreateDate = DateTime.Now;

                _context.Add(entity);
                return _context.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改功能
        /// </summary>
        /// <param name="entity">修改实体</param>
        /// <returns></returns>
        public async Task<int> Update(Management entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                return await _context.SaveChangesAsync(); 
            }
            catch (Exception)
            {
                throw;
            }
        }



        /// <summary>
        /// 执行单个逻辑删除操作
        /// </summary>
        /// <param name="id">要逻辑删除的条目的唯一标识符</param>
        /// <returns>返回一个表示异步操作的任务，任务结果为受影响的行数</returns>
        public Task<int> Delete(int id)
        {
            var list = _context.Managements.FirstOrDefault(x => x.EarTagId == id);
            if (list != null)
            {
                list.IsDel = true;
                _context.Update(list);
            }
            return _context.SaveChangesAsync();
        }

        /// <summary>
        /// 执行批量逻辑删除操作
        /// </summary>
        /// <param name="ids">包含要逻辑删除的条目的唯一标识符集合</param>
        /// <returns>返回一个表示异步操作的任务，任务结果为受影响的行数</returns>
        public Task<int> DeleteRange(IEnumerable<int> ids)
        {
            foreach (var item in ids)
            {
                var list = _context.Managements.FirstOrDefault(x => x.EarTagId == item);
                if (list != null)
                {
                    list.IsDel = true;
                    _context.Update(list);
                }
            }
            return _context.SaveChangesAsync();
        }
    }
}
